﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Shapes;

namespace YFIN.View.Helper
{
    public class VerifyCode
    {
        public static KeyValuePair<string, WriteableBitmap> GetVerifyCode()
        {
            var r = new Random();
            var nums = new [] {r.Next(0, 20), r.Next(0, 2), r.Next(0, 20)};
            if(nums[0] < nums[2])
            {
                int t = nums[0];
                nums[0] = nums[2];
                nums[2] = t;
            }
            var numsStr = new[] { nums[0].ToString(), nums[1] == 0 ? "+" : "-", nums[2].ToString(), "=", "?"};
            var grid = new Grid();
            grid.Width = 120;
            grid.Height = 40;
            var canvas2 = new Canvas();
            var c = r.Next(3, 6);
            for (int i = 0; i < c; i++)
            {
                var buffer = new byte[3];
                var polyline = new Polyline();
                var solidColorBrush = new SolidColorBrush(Color.FromArgb(255, buffer[0], buffer[1], buffer[2]));
                polyline.Stroke = solidColorBrush;
                for (int j = 0; j < 2; j++)
                {
                    polyline.Points.Add(new Point(r.NextDouble() * 120, r.NextDouble() * 40));
                }
                r.NextBytes(buffer);
                polyline.StrokeThickness = r.NextDouble() + 0.5;
                canvas2.Children.Add(polyline);
            }
            grid.Children.Add(canvas2);
            var canvas1 = new Canvas();
            for (int i = 0; i < 5; i++)
            {
                var tb = new TextBlock();
                var b = new byte[3];
                r.NextBytes(b);
                var brush = new SolidColorBrush(Color.FromArgb(255, (byte)(b[0]/2), (byte)(b[1]/2), (byte)(b[2]/2)));
                tb.TextAlignment = TextAlignment.Center;
                tb.FontSize = r.Next(24, 30);
                tb.Foreground = brush;
                tb.Text = numsStr[i];
                tb.Projection = new PlaneProjection()
                {
                    RotationX = r.Next(-30, 30),
                    RotationY = r.Next(-30, 30),
                    RotationZ = r.Next(-10, 10)
                };
                canvas1.Children.Add(tb); 
                Canvas.SetLeft(tb, r.Next(2, 5) + i*25);
                Canvas.SetTop(tb, r.Next(0, 5));
            }
            grid.Children.Add(canvas1);
            var writeableBitmap = new WriteableBitmap(grid, new TransformGroup());
            writeableBitmap.Render(grid, new TransformGroup());
            string res = (nums[1] == 0 ? nums[0] + nums[2] : nums[0] - nums[2]).ToString();
            return new KeyValuePair<string, WriteableBitmap>(res, writeableBitmap);
        }
    }
}
